import Axios from "axios"
import { getToken } from "@/utils/auth"
import store from "@/store/index"

const axios = Axios.create({
  timeout: 30000,
  responseType: "json"
})
axios.interceptors.request.use((config) => {
  const token = getToken()
  console.log("token :>> ", token)
  if (token && !config.headers.noAuth) {
    config.headers.Authorization = "Bearer " + token
  }
  config.headers["Cache-Control"] = "no-cache"
  return config
})
axios.interceptors.response.use(
  (response) => {
    if (
      response &&
      response.data &&
      (response.data.code === "4001" ||
        response.data.code === "401" ||
        response.data.status === "401")
    ) {
      store.dispatch("auth/logout")
    }
    return response
  },
  (error) => {
    if (error && error.response) {
      if (
        (error.response.status === 401 || error.response.status === 410) &&
        !error.config.headers.ignoreAuth
      ) {
        error.message = "登录信息无效，请重新登录"
        store.dispatch("auth/logout")
      }
    } else if (error) {
      error.message = "网络错误，请检查网络连接状态"
    }
    return Promise.reject(error)
  }
)
export { axios }
